import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from "@/api"

const state = {
    code: '',
    token: localStorage.getItem('TOKEN'),
    userInfo: {}
};
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, data) {
        state.userInfo = data
    },
    //清除本地数据
    CLEAR(state) {
        state.token = '',
            //把仓库中的用户信息清空
            state.userInfo = {},
            //清除本地存储
            localStorage.removeItem('TOKEN')
    }
};
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone)
        // console.log(result);
        if (result.code == 200) {
            commit('GETCODE', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //用户注册
    async UserRegister({ commit }, data) {
        let result = await reqUserRegister(data)
        // console.log(result);
        if (result.code == 200) {
            return "ok"
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //登录业务
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data)
        //服务器会下发token，用户的唯一标识符
        //将来经常通过带token找服务器要用户信息进行展示
        // console.log(result);
        if (result.code == 200) {
            commit('USERLOGIN', result.data.token)
            //持久化存储token
            localStorage.setItem('TOKEN', result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //带着token向服务器要用户信息
    async getUserInfo({ commit }) {
        let result = await reqUserInfo()
        console.log(result);
        if (result.code == 200) {
            commit('GETUSERINFO', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //退出登录（清除数据）
    async reqLogout({ commit }) {
        //向服务器发请求，通知服务器清除token
        let result = await reqLogout()
        if (result.code == 200) {
            // action里不能操作state，提交mutation修改state
            commit('CLEAR')
        }
    }
};
const getters = {};
export default {
    state,
    mutations,
    actions,
    getters
}